#include "mex.h"
#include "math.h"
/*
 * find_halfspace_mex.c
 * same as find_halfspace.m
 */
 
int binary_search(double a[], int low, int high, double target[]) {
 
    int middle = 0;
    while (high>=low) 
    {
      middle = floor((low + high)/2);
      //printf("%d %d %d %f %f\n",low,middle,high,a[middle],target[0]);
      if (a[middle]==target[0])
        return middle + 1;
      else
      {
        if (a[middle] < target[0])
          low = middle + 1;
        else
          high = middle -1;
      }
    }
    return middle+1;
}
 
void find_halfspace_mex(double y[], double x[],double f[],int low, int high)
{
        y[0]=binary_search(x, low, high, f);
 
}
 
void mexFunction( int nlhs, mxArray *plhs[],
        int nrhs, const mxArray *prhs[] )
{
    double *x,*y, *f;
    size_t mrows,ncols,maxsize;
    /* Check for proper number of arguments. */
    if(nrhs != 2) {
        mexErrMsgIdAndTxt( "MATLAB:find_halfspace_mex:invalidNumInputs", "two inputs required.");
    } else if( nlhs >1) {
        mexErrMsgIdAndTxt( "MATLAB:timestwo:maxlhs", "Too many output arguments.");
    }
 
    /* The input must be a noncomplex scalar double.*/
    mrows = mxGetM(prhs[0]);
    ncols = mxGetN(prhs[0]);
 
    if (mrows > ncols)
        maxsize = mrows;
    else
        maxsize = ncols;
 
    /* Create matrix for the return argument. */
    plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
 
    /* Assign pointers to each input and output. */
    x = mxGetPr(prhs[0]);
    f = mxGetPr(prhs[1]);
 
    y = mxGetPr(plhs[0]);
   
 
   find_halfspace_mex(y,x,f,0,maxsize);
}